<template>
  <div class="main-container">
    <!-- 地图容器 -->
    <div class="maps-container">
      <div class="map-wrapper">
        <v-row>
          <v-col cols="6">
            <v-select
                v-model="selectedOsmValue"
                :items="osmOptions"
                label="选择地图文件"
                dense
            ></v-select>
          </v-col>
        </v-row>
<!--        <input type="file" @change="loadShpZip(0)" accept=".zip" />-->
        <div id="map1" ref="map1"></div>
      </div>
      <div class="map-wrapper">
        <v-row>
          <v-col cols="6">
            <v-select
                v-model="selectedValue"
                :items="availableOptions"
                label="选择地图文件"
                dense
            ></v-select>
          </v-col>
        </v-row>
<!--        <input type="file" @change="loadShpZip(1)" accept=".zip" />-->
        <div id="map2" ref="map2"></div>
      </div>
    </div>
  </div>

  <v-row class="data-container">
    <!-- 第一个数据框 -->
    <v-col cols="6">
      <v-card class="data-box">
        <v-toolbar flat dense height="32" class="toolbar-small" color="grey lighten-4">
          <v-toolbar-title class="text-subtitle-2">
            相似度匹配结果
            <v-btn small color="primary" class="ml-2" @click="fetchArrayData('getPartSim', selectedValue, selectedOsmValue, 0)">局部匹配</v-btn>
          </v-toolbar-title>
        </v-toolbar>

        <v-card-text>
          <v-list dense>
            <v-list-item v-for="(item, index) in currentItems" :key="index">
              <v-list-item-content>
                <!-- 显示 Sim 值和数组 -->
                Sim值为: {{ item.similarity.toFixed(2) }}
<!--                , 部分地区: {{ item.resultArray.join(",").split(",")[0]}}-->
                <v-btn small color="primary" class="ml-2" @click="handleButtonClick(item.resultArray,item.roadOBJECTIDs)">
                  第{{index+1}}个结果
                </v-btn>
              </v-list-item-content>
            </v-list-item>
          </v-list>

          <v-card-actions>
            <v-btn small :disabled="currentPage === 1" @click="prevPage">上一页</v-btn>
            <v-spacer></v-spacer>
            <span>第 {{ currentPage }} 页</span>
            <v-spacer></v-spacer>
            <v-btn small :disabled="currentPage === totalPages" @click="nextPage">下一页</v-btn>
          </v-card-actions>
        </v-card-text>
      </v-card>
    </v-col>

    <!-- 第二个数据框 -->
    <v-col cols="6">
      <v-card class="data-box">
        <v-toolbar flat dense height="32" class="toolbar-small" color="grey lighten-4">
          <v-toolbar-title class="text-subtitle-2">
            相似度匹配结果
            <v-btn small color="primary" class="ml-2" @click="fetchArrayData('OverAll', selectedValue, selectedOsmValue, 1)">全局匹配</v-btn>
          </v-toolbar-title>
        </v-toolbar>

        <v-card-text>
          <v-list dense>
            <v-list-item v-for="(item, index) in otherCurrentItems" :key="index">
              <v-list-item-content>
                <!-- 显示 Sim 值和数组 -->
                Sim值为: {{ item.similarity.toFixed(2) }}
<!--                , 部分地区: {{ item.resultArray.join(",").split(",")[0]}}-->
                <v-btn small color="primary" class="ml-2" @click="handleButtonClick(item.resultArray,item.roadOBJECTIDs)">
                  第{{index+1}}个结果
                </v-btn>
              </v-list-item-content>
            </v-list-item>
          </v-list>

          <v-card-actions>
            <v-btn small :disabled="otherCurrentPage === 1" @click="prevOtherPage">上一页</v-btn>
            <v-spacer></v-spacer>
            <span>第 {{ otherCurrentPage }} 页</span>
            <v-spacer></v-spacer>
            <v-btn small :disabled="otherCurrentPage === otherTotalPages" @click="nextOtherPage">下一页</v-btn>
          </v-card-actions>
        </v-card-text>
      </v-card>
    </v-col>
  </v-row>
</template>

<script>
import {ref, onMounted, computed, watch} from 'vue';
import L from 'leaflet';
import shp from 'shpjs'; // 确保安装了 shpjs
import 'leaflet/dist/leaflet.css';
import {spring1,spring2} from '@/linux';

// 使用 import 语法引入 Leaflet 默认图标
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';

// Leaflet 默认图标样式
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: markerIcon2x,
  iconUrl: markerIcon,
  shadowUrl: markerShadow,
});

export default {
  name: "Sketch",
  setup() {
    const mapInstances = ref([null, null]); // 用于存储多个地图实例
    const geojsonLayers = ref([null, null]); // 用于存储多个 GeoJSON 图层
    const arrayData = ref([[], []]); // 用于存储两个数据框的数组数据
    const currentPage = ref(1); // 当前页
    const otherCurrentPage = ref(1); // 另一个数据框的当前页
    const itemsPerPage = 5; // 每页显示的项目数
    const selectedValue = ref("S1"); // 默认选择的值
    const availableOptions = ref(["S1","S2","S3","S4","S5","S6","S7","S8","S9","S12", "S13"]); // 可选项列表
    const selectedOsmValue = ref("xianlin");// 默认选择的值
    const osmOptions = ref(["xianlin","nanjingMESO"]); // 可选项列表


    onMounted(() => {
      // 创建两个地图实例
      mapInstances.value[0] = L.map('map1').setView([0, 0], 2); // 第一个地图
      mapInstances.value[1] = L.map('map2').setView([0, 0], 2); // 第二个地图

      loadShpZip(0, "xianlin.zip")
      loadShpZip(1, "S1.zip")
    });

    const fetchArrayData = async (end,caoTu,osm, index) => {
      try {
        const response = await fetch(spring2+"/data/"+end+"?caoTuLabel="+caoTu+"Group&realLabel="+osm+"Group"); // 动态构建请求 URL
        if (!response.ok) {
          throw new Error('网络响应不是 OK');
        }
        const result = await response.json(); // 假设返回的是 JSON 格式的数组
        console.log(result.data); // 打印返回的数据
        arrayData.value[index] = result.data; // 将获取的数据填充到对应的数组中
      } catch (error) {
        console.error('获取数组数据时出错:', error);
      }
    };

    // 计算总页数
    const totalPages = computed(() => Math.ceil(arrayData.value[0].length / itemsPerPage));
    const otherTotalPages = computed(() => Math.ceil(arrayData.value[1].length / itemsPerPage));

    // 计算当前页的数据
    const currentItems = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      return arrayData.value[0].slice(start, start + itemsPerPage);
    });

    const otherCurrentItems = computed(() => {
      const start = (otherCurrentPage.value - 1) * itemsPerPage;
      return arrayData.value[1].slice(start, start + itemsPerPage);
    });

    // 处理按钮点击事件
    const handleButtonClick = (resultArray,roadOBJECTIDs) => {
      resetHighlight(); // 清除之前的高亮
      console.log('高亮这组数据:', resultArray); // 处理按钮点击事件
      resultArray.forEach((itemKey) => {
        highlightSpecificFeature(0, itemKey); // 调用高亮函数
      });
      roadOBJECTIDs.forEach((itemKey) => {
        highlightSpecificRoad(0, itemKey); // 调用高亮函数
      });
    };

    // 上一页和下一页逻辑
    const prevPage = () => { if (currentPage.value > 1) currentPage.value--; };
    const nextPage = () => { if (currentPage.value < totalPages.value) currentPage.value++; };
    const prevOtherPage = () => { if (otherCurrentPage.value > 1) otherCurrentPage.value--; };
    const nextOtherPage = () => { if (otherCurrentPage.value < otherTotalPages.value) otherCurrentPage.value++; };


    const loadShpZip = (index, mapName) => {
      let fileInput = null;
      let file = null;

      // 清除旧的 GeoJSON 图层
      if (geojsonLayers.value[index]) {
        mapInstances.value[index].removeLayer(geojsonLayers.value[index]); // 从地图中移除旧图层
        geojsonLayers.value[index] = null; // 清空引用
      }

      // 获取触发事件文件输入
      if (mapName == null) {
        fileInput = event.target;
        file = fileInput.files[0];
      } else {
        // 从后端获取 ZIP 文件
        fetch(spring1+'/file/content?filename=' + mapName) // 替换为你的文件名
          .then(response => {
            if (!response.ok) {
              throw new Error('网络响应不是 OK');
            }
            return response.arrayBuffer(); // 读取为 ArrayBuffer
          })
          .then(arrayBuffer => {
            const reader = new FileReader();
            reader.onload = function () {
              const result = reader.result; // 读取的结果
              console.log('后端文件内容:', result); // 处理文件内容

              shp(result).then((geojson) => {
                console.log(`加载的 GeoJSON (地图 ${index + 1}):`, geojson);

                geojsonLayers.value[index] = L.geoJSON(geojson, {
                  onEachFeature: (feature, layer) => {
                    layer.on({
                      mousedown: () => {
                        if (layer.options.highlighted) {
                          resetHighlight(layer);
                          layer.options.highlighted = false;
                        } else {
                          highlightFeature(layer);
                          layer.options.highlighted = true;
                        }
                      },
                    });
                  },
                  style: {
                    color: "#3388ff",
                    weight: 2,
                    opacity: 1,
                  },
                }).addTo(mapInstances.value[index]);

                mapInstances.value[index].fitBounds(geojsonLayers.value[index].getBounds());

              }).catch((error) => {
                console.error('解析后端 ZIP 文件时出错:', error);
              });
            };
            reader.readAsArrayBuffer(new Blob([arrayBuffer]));
          })
          .catch(error => {
            console.error('获取后端文件时出错:', error);
          });
      }
      // 处理用户选择的本地 ZIP 文件
      if (file && file.name.endsWith('.zip')) {
        const localReader = new FileReader();
        localReader.readAsArrayBuffer(file);
        localReader.onload = () => {
          shp(localReader.result).then((geojson) => {
            console.log(`加载的 GeoJSON (地图 ${index + 1}):`, geojson);

            geojsonLayers.value[index] = L.geoJSON(geojson, {
              onEachFeature: (feature, layer) => {
                layer.on({
                  mousedown: () => {
                    if (layer.options.highlighted) {
                      resetHighlight(layer);
                      layer.options.highlighted = false;
                    } else {
                      highlightFeature(layer);
                      layer.options.highlighted = true;
                    }
                  },
                });
              },
              style: {
                color: "#3388ff",
                weight: 2,
                opacity: 1,
              },
            }).addTo(mapInstances.value[index]);

            mapInstances.value[index].fitBounds(geojsonLayers.value[index].getBounds());

          }).catch((error) => {
            console.error('解析本地 ZIP 文件时出错:', error);
          });
        };
      }
    };

    const highlightFeature = (layer) => {
      layer.setStyle({
        weight: 5,
        color: "#ff7800",
        dashArray: '',
        fillOpacity: 0.7,
      });
    };

    const highlightRoad = (layer) => {
      layer.setStyle({
        weight: 5,
        color: "#ff0000",
        dashArray: '',
        fillOpacity: 0.7,
      });
    };

    const resetHighlight = (layer) => {
      geojsonLayers.value.forEach((geojsonLayer) => {
        if (geojsonLayer) {
          geojsonLayer.resetStyle(layer);
        }
      });
    };

    const highlightSpecificFeature = (index, objectId) => {
      geojsonLayers.value[index].eachLayer((layer) => {
        if (layer.feature && layer.feature.properties.OBJECTID === objectId) {
          highlightFeature(layer);
        }
      });
    };

    const highlightSpecificRoad = (index, objectId) => {
      geojsonLayers.value[index].eachLayer((layer) => {
        if (layer.feature && layer.feature.properties.OBJECTID === objectId) {
          highlightRoad(layer);
        }
      });
    };

    // 监听选择器的值变化
    watch(selectedValue, (newValue) => {
      console.log(`选择器值变化: ${newValue}`);
      loadShpZip(1, `${newValue}.zip`); // 根据新值重新加载地图
    });

    return {
      loadShpZip,
      arrayData,
      currentItems,
      otherCurrentItems,
      currentPage,
      otherCurrentPage,
      totalPages,
      otherTotalPages,
      handleButtonClick,
      prevPage,
      nextPage,
      prevOtherPage,
      nextOtherPage,
      fetchArrayData,
      availableOptions,
      selectedValue,
      osmOptions,
      selectedOsmValue,
    };
  },
};
</script>

<style>
.main-container {
  display: flex;
  flex-direction: column;
}

.maps-container {
  display: flex;
  justify-content: space-between;
}

.map-wrapper {
  width: 48%;
}

#map1,
#map2 {
  height: 400px; /* 设置地图高度 */
  border: 1px solid #ccc;
}

.data-container {
  margin-top: 20px; /* 调整数据框与地图之间的距离 */
}

.data-box {
  margin-top: 2px;
}
</style>